package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class OrderReceiver {

    //  注入订单服务层对象.
    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void  orderCancel(Long orderId, Message message, Channel channel){
        //  判断当前 orderId orderInfo ---> paymentInfo ----> aLipay;   关闭的数据. aLipay--->paymentInfo -----> orderInfo;
        try {
            if (orderId!=null){
                //  查询订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                if ("UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  判断是否有交易记录.
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    if (paymentInfo!=null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        //   先查询,考虑是否需要关闭支付宝交易记录.
                        Boolean exist = paymentFeignClient.checkPayment(orderId);
                        if (exist){
                            //  有交易记录. 有可能需要关闭支付。
                            //  支付成功了，就不能关闭支付宝交易记录!
                            Boolean result = paymentFeignClient.closePay(orderId);
                            if (result){
                                //  关闭成功: 说明这个人没有支付!
                                //  关闭orderInfo + paymentInfo;
                                orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //  说明关闭失败：用户支付成功了. 不需要因为有异步回调！
                            }
                        } else {
                            //  关闭orderInfo + paymentInfo;
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    } else {
                        //  调用取消订单方法.
                        //  orderService.execExpiredOrder(orderId); // orderInfo + paymentInfo;
                        //  不需要发送消息关闭paymentInfo;
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER_CLOSED,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER_CLOSED),
            key = {MqConst.ROUTING_ORDER_CLOSED}
    ))
    public void  orderClosed(Long orderId, Message message, Channel channel){
        //  判断当前orderId
        try {
            if (orderId!=null){
                //  查询订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                if (!"CLOSED".equals(orderInfo.getOrderStatus()) && !"CLOSED".equals(orderInfo.getProcessStatus())){
                    //  调用关闭订单方法.
                    orderService.updateOrderStatus(orderId, ProcessStatus.CLOSED);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  修改订单状态为支付！
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void paymentPay(Long orderId, Message message, Channel channel){
        //  判断当前orderId
        try {
            if (orderId!=null){
                //  查询订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                if ("UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  调用关闭订单方法.
                    orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                    //  发送消息给库存系统.
                    orderService.sendOrderStatus(orderId);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听库存减库存结果.
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void wareOrder(String strJson,Message message, Channel channel){
        try {
            //  判断
            if(!StringUtils.isEmpty(strJson)){
                //  将数据转为Map 集合
                Map map = JSON.parseObject(strJson, Map.class);
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                //  判断减库存结果.
                if ("DEDUCTED".equals(status)){
                    //  减库存成功，更新订单状态.
                    orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
                } else {
                    //  说明库存异常. 当前剩余商品数量<购买数据.  记录这个消息--消息记录表：补货，如果补货成功。手动发送消息更新减库存的结果.
                    orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
                }
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        }

        //  手动签收
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
